"use strict";
const BaseImpl = require("../basics/clz/baseimpl");
const Result = require("../basics/result");
const MasterModel = require("../model/master");
const TempModel = require("../model/temp");
const LiveApi = require("../taobao/live");

/**
 * 通用服务
 */
class HomeImpl extends BaseImpl {


  /**
   * 编辑app
   * @param {*} params 
   */
  async editAppId(params) {
    let { userId, appId } = params;
    const tempModel = TempModel.getInstant(this.cloud);
    let record = await tempModel.selectOneByAppId(appId);
    if (record) {
      return true;
    }
    const master = await MasterModel.getInstant(this.cloud).selectOneById(userId);
    if (!master) {
      throw Result.error(Result.constant.taobaofail, "未知用户");
    }
    record = { openId: master.openId, userNick: master.userNick, shopId: master.shopId, sellerId: master.sellerId, shopUrl: master.shopUrl, appId };
    await tempModel.insertOne(record);
    return true;
  }
  /**
   * 查询店铺
   * @param {String} appId 
   */
  async findTeamp(appId) {
    if (!appId) {
      return null;
    }
    const master = await TempModel.getInstant(this.cloud).selectOneByAppId(appId);
    if (!master) {
      return null;
    }
    return { shopId: master.shopId, sellerId: master.sellerId, appId: master.appId, shopUrl: master.shopUrl };
  }

  /**
   * 小部件初始化
   * @param {*} param 
   */
  async initTeamp(param) {
    let { entity_id, template_id, template_version, authToken } = param;
    if (!template_id || !template_version || !authToken) {
      throw Result.error(Result.constant.taobaofail, "参数错误！！！");
    }
    //已实例化过的，走实例化更新流程
    if (entity_id) {
      return await LiveApi.updateapp(this.cloud, authToken, { entity_id, template_id, template_version });
    }
    const description = "小部件实例化可进行整体实例化流程";
    return await LiveApi.instantiate(this.cloud, authToken, { description, template_id, template_version });
  }
}
module.exports = HomeImpl;